package cn.iocoder.yudao.module.crossborder.platform.service.provider.amazon.client;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * Amazon SP-API 模拟服务
 * 用于测试环境模拟Amazon SP-API的响应数据
 *
 * @author 芋道源码
 */
@Service
@Slf4j
@ConditionalOnProperty(name = "amazon.api.mock.enabled", havingValue = "true", matchIfMissing = false)
public class AmazonApiMockService {

    private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
    private final Random random = new Random();

    /**
     * 模拟获取订单列表
     */
    public Map<String, Object> mockGetOrders(Map<String, String> queryParams) {
        log.info("模拟获取Amazon订单列表: {}", queryParams);

        Map<String, Object> response = new HashMap<>();
        Map<String, Object> payload = new HashMap<>();
        
        // 生成模拟订单数据
        List<Map<String, Object>> orders = generateMockOrders(10);
        payload.put("Orders", orders);
        payload.put("NextToken", null);
        payload.put("CreatedBefore", LocalDateTime.now().format(dateTimeFormatter));
        
        response.put("payload", payload);
        response.put("success", true);
        
        return response;
    }

    /**
     * 模拟获取订单详情
     */
    public Map<String, Object> mockGetOrder(String orderId) {
        log.info("模拟获取Amazon订单详情: {}", orderId);

        Map<String, Object> response = new HashMap<>();
        Map<String, Object> payload = new HashMap<>();
        
        // 生成单个订单详情
        Map<String, Object> order = generateMockOrderDetail(orderId);
        payload.put("Order", order);
        
        response.put("payload", payload);
        response.put("success", true);
        
        return response;
    }

    /**
     * 模拟获取订单商品
     */
    public Map<String, Object> mockGetOrderItems(String orderId) {
        log.info("模拟获取Amazon订单商品: {}", orderId);

        Map<String, Object> response = new HashMap<>();
        Map<String, Object> payload = new HashMap<>();
        
        // 生成订单商品列表
        List<Map<String, Object>> orderItems = generateMockOrderItems(orderId);
        payload.put("OrderItems", orderItems);
        payload.put("NextToken", null);
        
        response.put("payload", payload);
        response.put("success", true);
        
        return response;
    }

    /**
     * 模拟获取商品目录
     */
    public Map<String, Object> mockGetCatalogItems(Map<String, String> queryParams) {
        log.info("模拟获取Amazon商品目录: {}", queryParams);

        Map<String, Object> response = new HashMap<>();
        Map<String, Object> payload = new HashMap<>();
        
        // 生成模拟商品数据
        List<Map<String, Object>> items = generateMockCatalogItems(20);
        payload.put("Items", items);
        payload.put("NextToken", null);
        
        response.put("payload", payload);
        response.put("success", true);
        
        return response;
    }

    /**
     * 模拟获取商品详情
     */
    public Map<String, Object> mockGetCatalogItem(String asin) {
        log.info("模拟获取Amazon商品详情: {}", asin);

        Map<String, Object> response = new HashMap<>();
        Map<String, Object> payload = new HashMap<>();
        
        // 生成单个商品详情
        Map<String, Object> item = generateMockCatalogItemDetail(asin);
        payload.put("Item", item);
        
        response.put("payload", payload);
        response.put("success", true);
        
        return response;
    }

    /**
     * 模拟获取库存汇总
     */
    public Map<String, Object> mockGetInventorySummaries(Map<String, String> queryParams) {
        log.info("模拟获取Amazon库存汇总: {}", queryParams);

        Map<String, Object> response = new HashMap<>();
        Map<String, Object> payload = new HashMap<>();
        
        // 生成模拟库存数据
        List<Map<String, Object>> inventorySummaries = generateMockInventorySummaries(15);
        payload.put("InventorySummaries", inventorySummaries);
        payload.put("NextToken", null);
        
        response.put("payload", payload);
        response.put("success", true);
        
        return response;
    }

    /**
     * 模拟健康检查
     */
    public Map<String, Object> mockHealthCheck() {
        log.info("模拟Amazon API健康检查");

        Map<String, Object> response = new HashMap<>();
        response.put("status", "healthy");
        response.put("timestamp", LocalDateTime.now().format(dateTimeFormatter));
        response.put("success", true);
        
        return response;
    }

    /**
     * 模拟用户配置文件
     */
    public Map<String, Object> mockGetUserProfile() {
        log.info("模拟获取Amazon用户配置文件");

        Map<String, Object> response = new HashMap<>();
        Map<String, Object> payload = new HashMap<>();
        
        payload.put("sellerId", "MOCK_SELLER_" + System.currentTimeMillis());
        payload.put("sellerName", "Mock Amazon Seller");
        payload.put("marketplaceIds", Arrays.asList("ATVPDKIKX0DER", "A2EUQ1WTGCTBG2"));
        
        response.put("payload", payload);
        response.put("success", true);
        
        return response;
    }

    // ==================== 私有方法：生成模拟数据 ====================

    /**
     * 生成模拟订单列表
     */
    private List<Map<String, Object>> generateMockOrders(int count) {
        List<Map<String, Object>> orders = new ArrayList<>();
        
        for (int i = 0; i < count; i++) {
            Map<String, Object> order = new HashMap<>();
            order.put("AmazonOrderId", "MOCK-ORDER-" + (System.currentTimeMillis() + i));
            order.put("SellerOrderId", "SO-" + (1000 + i));
            order.put("PurchaseDate", LocalDateTime.now().minusDays(random.nextInt(30)).format(dateTimeFormatter));
            order.put("LastUpdateDate", LocalDateTime.now().minusDays(random.nextInt(5)).format(dateTimeFormatter));
            order.put("OrderStatus", getRandomOrderStatus());
            order.put("FulfillmentChannel", random.nextBoolean() ? "MFN" : "AFN");
            order.put("SalesChannel", "Amazon.com");
            order.put("OrderChannel", "Online");
            order.put("ShipServiceLevel", "Standard");
            order.put("OrderTotal", createMockMoney(50 + random.nextDouble() * 200));
            order.put("NumberOfItemsShipped", random.nextInt(5) + 1);
            order.put("NumberOfItemsUnshipped", random.nextInt(2));
            order.put("PaymentMethod", "Other");
            order.put("PaymentMethodDetails", Arrays.asList("Standard"));
            order.put("MarketplaceId", "ATVPDKIKX0DER");
            order.put("ShipmentServiceLevelCategory", "Standard");
            order.put("OrderType", "StandardOrder");
            order.put("EarliestShipDate", LocalDateTime.now().plusDays(1).format(dateTimeFormatter));
            order.put("LatestShipDate", LocalDateTime.now().plusDays(3).format(dateTimeFormatter));
            order.put("IsBusinessOrder", false);
            order.put("IsPrime", random.nextBoolean());
            order.put("IsGlobalExpressEnabled", false);
            order.put("IsPremiumOrder", false);
            order.put("IsReplacementOrder", false);
            
            orders.add(order);
        }
        
        return orders;
    }

    /**
     * 生成模拟订单详情
     */
    private Map<String, Object> generateMockOrderDetail(String orderId) {
        Map<String, Object> order = new HashMap<>();
        order.put("AmazonOrderId", orderId);
        order.put("SellerOrderId", "SO-" + orderId.substring(orderId.length() - 6));
        order.put("PurchaseDate", LocalDateTime.now().minusDays(random.nextInt(30)).format(dateTimeFormatter));
        order.put("LastUpdateDate", LocalDateTime.now().minusDays(random.nextInt(5)).format(dateTimeFormatter));
        order.put("OrderStatus", getRandomOrderStatus());
        order.put("FulfillmentChannel", random.nextBoolean() ? "MFN" : "AFN");
        order.put("SalesChannel", "Amazon.com");
        order.put("OrderChannel", "Online");
        order.put("ShipServiceLevel", "Standard");
        order.put("OrderTotal", createMockMoney(50 + random.nextDouble() * 200));
        order.put("NumberOfItemsShipped", random.nextInt(5) + 1);
        order.put("NumberOfItemsUnshipped", random.nextInt(2));
        order.put("PaymentMethod", "Other");
        order.put("PaymentMethodDetails", Arrays.asList("Standard"));
        order.put("MarketplaceId", "ATVPDKIKX0DER");
        order.put("ShipmentServiceLevelCategory", "Standard");
        order.put("OrderType", "StandardOrder");
        order.put("EarliestShipDate", LocalDateTime.now().plusDays(1).format(dateTimeFormatter));
        order.put("LatestShipDate", LocalDateTime.now().plusDays(3).format(dateTimeFormatter));
        order.put("IsBusinessOrder", false);
        order.put("IsPrime", random.nextBoolean());
        order.put("IsGlobalExpressEnabled", false);
        order.put("IsPremiumOrder", false);
        order.put("IsReplacementOrder", false);
        
        // 添加收货地址
        Map<String, Object> shippingAddress = new HashMap<>();
        shippingAddress.put("Name", "Mock Customer");
        shippingAddress.put("AddressLine1", "123 Mock Street");
        shippingAddress.put("City", "Mock City");
        shippingAddress.put("StateOrRegion", "CA");
        shippingAddress.put("PostalCode", "90210");
        shippingAddress.put("CountryCode", "US");
        order.put("ShippingAddress", shippingAddress);
        
        return order;
    }

    /**
     * 生成模拟订单商品
     */
    private List<Map<String, Object>> generateMockOrderItems(String orderId) {
        List<Map<String, Object>> orderItems = new ArrayList<>();
        int itemCount = random.nextInt(3) + 1; // 1-3个商品
        
        for (int i = 0; i < itemCount; i++) {
            Map<String, Object> item = new HashMap<>();
            item.put("ASIN", "B" + String.format("%09d", random.nextInt(1000000000)));
            item.put("SellerSKU", "SKU-" + (1000 + i));
            item.put("OrderItemId", orderId + "-ITEM-" + (i + 1));
            item.put("Title", "Mock Product " + (i + 1));
            item.put("QuantityOrdered", random.nextInt(3) + 1);
            item.put("QuantityShipped", random.nextInt(3) + 1);
            item.put("ItemPrice", createMockMoney(20 + random.nextDouble() * 80));
            item.put("ItemTax", createMockMoney(1 + random.nextDouble() * 5));
            item.put("ShippingPrice", createMockMoney(random.nextDouble() * 10));
            item.put("ShippingTax", createMockMoney(random.nextDouble() * 2));
            item.put("GiftWrapPrice", createMockMoney(0));
            item.put("GiftWrapTax", createMockMoney(0));
            item.put("ItemPromotionDiscount", createMockMoney(0));
            item.put("ShippingPromotionDiscount", createMockMoney(0));
            item.put("PromotionIds", new ArrayList<>());
            item.put("CODFee", createMockMoney(0));
            item.put("CODFeeDiscount", createMockMoney(0));
            item.put("IsGift", false);
            item.put("ConditionNote", "");
            item.put("ConditionId", "New");
            item.put("ConditionSubtypeId", "New");
            
            orderItems.add(item);
        }
        
        return orderItems;
    }

    /**
     * 生成模拟商品目录
     */
    private List<Map<String, Object>> generateMockCatalogItems(int count) {
        List<Map<String, Object>> items = new ArrayList<>();

        for (int i = 0; i < count; i++) {
            Map<String, Object> item = new HashMap<>();
            item.put("Asin", "B" + String.format("%09d", random.nextInt(1000000000)));
            item.put("SellerSku", "SKU-" + (1000 + i));

            // 商品属性
            Map<String, Object> attributes = new HashMap<>();
            attributes.put("item_name", Arrays.asList(createMockAttribute("Mock Product " + (i + 1))));
            attributes.put("brand", Arrays.asList(createMockAttribute("Mock Brand")));
            attributes.put("manufacturer", Arrays.asList(createMockAttribute("Mock Manufacturer")));
            attributes.put("item_type_name", Arrays.asList(createMockAttribute("PRODUCT")));
            attributes.put("product_category", Arrays.asList(createMockAttribute("Electronics")));
            attributes.put("list_price", Arrays.asList(createMockPriceAttribute(50 + random.nextDouble() * 200)));

            item.put("Attributes", attributes);

            // 商品标识符
            Map<String, Object> identifiers = new HashMap<>();
            identifiers.put("MarketplaceASIN", createMockMarketplaceAsin(item.get("Asin").toString()));
            item.put("Identifiers", identifiers);

            // 图片信息
            List<Map<String, Object>> images = new ArrayList<>();
            Map<String, Object> image = new HashMap<>();
            image.put("Variant", "MAIN");
            image.put("Link", "https://mock-images.amazon.com/images/I/mock-image-" + i + ".jpg");
            image.put("Height", 500);
            image.put("Width", 500);
            images.add(image);
            item.put("Images", images);

            // 销售排名
            List<Map<String, Object>> salesRanks = new ArrayList<>();
            Map<String, Object> salesRank = new HashMap<>();
            salesRank.put("ProductCategoryId", "electronics");
            salesRank.put("Rank", random.nextInt(100000) + 1);
            salesRank.put("Title", "Electronics");
            salesRanks.add(salesRank);
            item.put("SalesRanks", salesRanks);

            items.add(item);
        }

        return items;
    }

    /**
     * 生成模拟商品详情
     */
    private Map<String, Object> generateMockCatalogItemDetail(String asin) {
        Map<String, Object> item = new HashMap<>();
        item.put("Asin", asin);

        // 商品属性
        Map<String, Object> attributes = new HashMap<>();
        attributes.put("item_name", Arrays.asList(createMockAttribute("Mock Product for " + asin)));
        attributes.put("brand", Arrays.asList(createMockAttribute("Mock Brand")));
        attributes.put("manufacturer", Arrays.asList(createMockAttribute("Mock Manufacturer")));
        attributes.put("item_type_name", Arrays.asList(createMockAttribute("PRODUCT")));
        attributes.put("product_category", Arrays.asList(createMockAttribute("Electronics")));
        attributes.put("list_price", Arrays.asList(createMockPriceAttribute(50 + random.nextDouble() * 200)));
        attributes.put("item_weight", Arrays.asList(createMockDimensionAttribute(1.5, "pounds")));
        attributes.put("item_dimensions", Arrays.asList(createMockDimensionAttribute(10.0, "inches")));
        attributes.put("color", Arrays.asList(createMockAttribute("Black")));
        attributes.put("size", Arrays.asList(createMockAttribute("Medium")));

        item.put("Attributes", attributes);

        // 商品标识符
        Map<String, Object> identifiers = new HashMap<>();
        identifiers.put("MarketplaceASIN", createMockMarketplaceAsin(asin));
        item.put("Identifiers", identifiers);

        // 图片信息
        List<Map<String, Object>> images = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Map<String, Object> image = new HashMap<>();
            image.put("Variant", i == 0 ? "MAIN" : "PT" + i);
            image.put("Link", "https://mock-images.amazon.com/images/I/mock-image-" + asin + "-" + i + ".jpg");
            image.put("Height", 500);
            image.put("Width", 500);
            images.add(image);
        }
        item.put("Images", images);

        // 销售排名
        List<Map<String, Object>> salesRanks = new ArrayList<>();
        Map<String, Object> salesRank = new HashMap<>();
        salesRank.put("ProductCategoryId", "electronics");
        salesRank.put("Rank", random.nextInt(100000) + 1);
        salesRank.put("Title", "Electronics");
        salesRanks.add(salesRank);
        item.put("SalesRanks", salesRanks);

        // 变体信息
        List<Map<String, Object>> variations = new ArrayList<>();
        Map<String, Object> variation = new HashMap<>();
        variation.put("Asin", asin);

        // JDK 1.8兼容的Map创建方式
        Map<String, Object> attributes2 = new HashMap<>();
        attributes2.put("color", "Black");
        attributes2.put("size", "Medium");
        variation.put("Attributes", attributes2);

        variations.add(variation);
        item.put("Variations", variations);

        return item;
    }

    /**
     * 生成模拟库存汇总
     */
    private List<Map<String, Object>> generateMockInventorySummaries(int count) {
        List<Map<String, Object>> inventorySummaries = new ArrayList<>();

        for (int i = 0; i < count; i++) {
            Map<String, Object> summary = new HashMap<>();
            summary.put("Asin", "B" + String.format("%09d", random.nextInt(1000000000)));
            summary.put("FnSku", "FN-SKU-" + (1000 + i));
            summary.put("SellerSku", "SKU-" + (1000 + i));
            summary.put("Condition", "NewItem");
            summary.put("InventoryDetails", createMockInventoryDetails());
            summary.put("LastUpdatedTime", LocalDateTime.now().minusDays(random.nextInt(7)).format(dateTimeFormatter));
            summary.put("ProductName", "Mock Product " + (i + 1));
            summary.put("TotalQuantity", random.nextInt(1000) + 10);

            inventorySummaries.add(summary);
        }

        return inventorySummaries;
    }

    // ==================== 辅助方法 ====================

    /**
     * 获取随机订单状态
     */
    private String getRandomOrderStatus() {
        String[] statuses = {"Pending", "Unshipped", "PartiallyShipped", "Shipped", "Canceled", "Unfulfillable"};
        return statuses[random.nextInt(statuses.length)];
    }

    /**
     * 创建模拟金额对象
     */
    private Map<String, Object> createMockMoney(double amount) {
        Map<String, Object> money = new HashMap<>();
        money.put("CurrencyCode", "USD");
        money.put("Amount", String.format("%.2f", amount));
        return money;
    }

    /**
     * 创建模拟属性
     */
    private Map<String, Object> createMockAttribute(String value) {
        Map<String, Object> attribute = new HashMap<>();
        attribute.put("Value", value);
        attribute.put("ValueType", "STRING");
        return attribute;
    }

    /**
     * 创建模拟价格属性
     */
    private Map<String, Object> createMockPriceAttribute(double amount) {
        Map<String, Object> attribute = new HashMap<>();
        attribute.put("Value", String.format("%.2f", amount));
        attribute.put("ValueType", "PRICE");
        attribute.put("CurrencyCode", "USD");
        return attribute;
    }

    /**
     * 创建模拟尺寸属性
     */
    private Map<String, Object> createMockDimensionAttribute(double value, String unit) {
        Map<String, Object> attribute = new HashMap<>();
        attribute.put("Value", String.valueOf(value));
        attribute.put("ValueType", "DIMENSION");
        attribute.put("Unit", unit);
        return attribute;
    }

    /**
     * 创建模拟市场ASIN
     */
    private Map<String, Object> createMockMarketplaceAsin(String asin) {
        Map<String, Object> marketplaceAsin = new HashMap<>();
        marketplaceAsin.put("MarketplaceId", "ATVPDKIKX0DER");
        marketplaceAsin.put("ASIN", asin);
        return marketplaceAsin;
    }

    /**
     * 创建模拟库存详情
     */
    private Map<String, Object> createMockInventoryDetails() {
        Map<String, Object> details = new HashMap<>();
        details.put("FulfillableQuantity", random.nextInt(500) + 10);
        details.put("InboundWorkingQuantity", random.nextInt(50));
        details.put("InboundShippedQuantity", random.nextInt(30));
        details.put("InboundReceivingQuantity", random.nextInt(20));
        details.put("ReservedQuantity", createMockReservedQuantity());
        details.put("UnfulfillableQuantity", random.nextInt(10));
        return details;
    }

    /**
     * 创建模拟预留库存
     */
    private Map<String, Object> createMockReservedQuantity() {
        Map<String, Object> reserved = new HashMap<>();
        reserved.put("TotalReservedQuantity", random.nextInt(20));
        reserved.put("PendingCustomerOrderQuantity", random.nextInt(10));
        reserved.put("PendingTransshipmentQuantity", random.nextInt(5));
        reserved.put("FcProcessingQuantity", random.nextInt(5));
        return reserved;
    }
}
